package com.atmilan.quartz.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import com.atmilan.quartz.utils.product.ViettiProductUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.atmilan.quartz.constant.Constants;
import com.atmilan.quartz.constant.enums.ProductTypeEnum;
import com.atmilan.quartz.constant.enums.SyncStatusEnum;
import com.atmilan.quartz.model.dto.crmeb.StoreProductCrmebRequest;
import com.atmilan.quartz.model.dto.vietti.ViettiProductResDTO;
import com.atmilan.quartz.model.dto.vietti.ViettiProductResDTO.Goods;
import com.atmilan.quartz.model.dto.vietti.ViettiProductSkuRes;
import com.atmilan.quartz.model.dto.vietti.ViettiProductSkuResDTO.Sku;
import com.atmilan.quartz.model.entity.crmeb.CategoryMatch;
import com.atmilan.quartz.model.entity.crmeb.StoreProduct;
import com.atmilan.quartz.model.entity.crmeb.SystemConfig;
import com.atmilan.quartz.model.entity.vietti.ViettiProduct;
import com.atmilan.quartz.model.entity.vietti.ViettiProductSku;
import com.atmilan.quartz.service.ICategoryMatchService;
import com.atmilan.quartz.service.IStoreProductAttrService;
import com.atmilan.quartz.service.IStoreProductAttrValueService;
import com.atmilan.quartz.service.IStoreProductService;
import com.atmilan.quartz.service.ISystemConfigService;
import com.atmilan.quartz.service.IViettiProductService;
import com.atmilan.quartz.service.IViettiProductSkuService;
import com.atmilan.quartz.service.IViettiSyncService;
import com.atmilan.quartz.utils.RedisUtil;
import com.atmilan.quartz.utils.source.SourceViettiProductUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import lombok.extern.slf4j.Slf4j;

/**
 * @author Howe Hsiang
 */
@Slf4j
@Service
public class ViettiSyncServiceImpl implements IViettiSyncService {
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    ISystemConfigService systemConfigService;
    @Autowired
    IViettiProductService viettiProductService;
    @Autowired
    IViettiProductSkuService viettiProductSkuService;
    @Autowired
    IStoreProductService storeProductService;
    @Autowired
    IStoreProductAttrService storeProductAttrService;
    @Autowired
    IStoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    SourceViettiProductUtil sourceViettiProductUtil;
    @Autowired
    ICategoryMatchService categoryMatchService;
    @Autowired
    ViettiProductUtil viettiProductUtil;
    
    /**
     * 获取远程数据并保存到数据源
     */
    @Override
    public Boolean syncProduct() {
        // 数据清空
        viettiProductService.deleteAll();
        viettiProductSkuService.deleteAll();

        int pageNo = 1;
        int pageCount = 1;
        long millis = System.currentTimeMillis();
        while(pageNo <= pageCount) {
            try {
                ViettiProductResDTO viettiProductResDTO = viettiProductUtil.selectViettiPage();
                if(null == viettiProductResDTO) {
                    log.info("--------------- vietti获取商品接口请求失败 ---------------");
                    continue;
                }
                List<Sku> skuList = new ArrayList<>();
                viettiProductResDTO.getGoodsList().forEach(good->{
                    ViettiProductSkuRes viettiProductSkuRes = viettiProductUtil.getViettiSku(good.getProductId());
                    if(!Objects.isNull(viettiProductSkuRes) && !Objects.isNull(viettiProductSkuRes.getSku()) && CollectionUtils.isNotEmpty(viettiProductSkuRes.getSku().getSizes())){
                        viettiProductSkuRes.getSku().getSizes().forEach(e->{
                            Sku sku = new Sku();
                            BeanUtils.copyProperties(viettiProductSkuRes.getSku(),sku);
                            BeanUtils.copyProperties(e,sku);
                            skuList.add(sku);
                        });
                    }
                });
                if(CollectionUtils.isEmpty(skuList)) {
                    log.info("--------------- vietti获取商品接口请求失败 ---------------");
                    continue;
                }
                
                List<Goods> goodsList = viettiProductResDTO.getGoodsList();
                // 商品保存
                saveGoods(goodsList, skuList);
                
            } catch (Exception e) {
                e.printStackTrace();
            }
            log.info("--------------- vietti远程抓取数据, 第: {} 页,  总共: {} 页, 总耗时: {} 分  ---------------", pageNo, pageCount, (int)((System.currentTimeMillis() - millis) / 1000 / 60));
            pageNo++;
        }
    
        return true;
    }
    
    // 商品源数据保存
    private void saveGoods(List<Goods> goodsList, List<Sku> skuList) {
        // 商品数据
        List<ViettiProduct> goodsEntity = new ArrayList<>();
        for(Goods goods : goodsList) {
            ViettiProduct productEntity = new ViettiProduct();
            BeanUtils.copyProperties(goods, productEntity);
            productEntity.setCustomData(JSONArray.toJSONString(goods.getCustomData()));
            productEntity.setSizes(JSONArray.toJSONString(goods.getSizes()));
            productEntity.setPhotos(JSONArray.toJSONString(goods.getPhotos()));
            productEntity.setCreateTime(new Date());
            goodsEntity.add(productEntity);
        }
        List<ViettiProductSku> productSkuEntity = new ArrayList<>();
        for(Sku sku : skuList) {
            ViettiProductSku skuEntity = new ViettiProductSku();
            BeanUtils.copyProperties(sku, skuEntity);
            skuEntity.setCreateTime(new Date());
            productSkuEntity.add(skuEntity);
        }
        
        viettiProductService.saveBatch(goodsEntity);
        viettiProductSkuService.saveBatch(productSkuEntity);
    }

    @Override
    public Boolean pushProduct() {
        try {
            // 当次更新少于1千条, 则不更新, 并且重新拉取
            int count = viettiProductService.count();
            if(1000 > count) {
                systemConfigService.update(Wrappers.<SystemConfig>lambdaUpdate()
                        .eq(SystemConfig :: getName, Constants.VIETTI_SYNC_STATUS)
                        .set(SystemConfig :: getFormId, SyncStatusEnum.PUSH)
                        .set(SystemConfig :: getUpdateTime, new Date())
                        );
                log.info("--------------- vietti商品源数据, 少于规定条数, 不进行下发, 总条数为: {} ---------------", count);
                return false;
            }
            
            // 将所有vietti商品更新状态置为未更新
            storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate()
                    .eq(StoreProduct :: getIsEurope, ProductTypeEnum.VIETTI.getCode())
                    .set(StoreProduct :: getUpdateFlag, false)
                    );
            
            // 商品更新操作
            int pageNo = 1;
            int pageSize = 100;
            int maxPage = (count + pageSize - 1) / pageSize;
            log.info("--------------- 开始分页查询vietti商品源数据, 本次更新总条数为: {} ---------------", count);

            long millis = System.currentTimeMillis();
            while (pageNo <= maxPage) {
                try {
                    PageHelper.startPage(pageNo, pageSize);
                    List<ViettiProduct> viettiProducts = viettiProductService.list();
                    PageInfo<ViettiProduct> pageInfo = PageInfo.of(viettiProducts);
                    List<ViettiProduct> products = pageInfo.getList();
                    buildProduct(products);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                log.info("--------------- vietti下发商品到数据库, 当前页数: {}, 总页数: {}, 耗时: {} 分 ---------------", pageNo, maxPage, (int)((System.currentTimeMillis() - millis) / 1000 / 60));
                pageNo++;
            }
            // 图搜删除
            storeProductService.delSeachImage(ProductTypeEnum.VIETTI);
            // 下架所有未更新数据
            storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate()
                    .eq(StoreProduct::getIsEurope, ProductTypeEnum.VIETTI.getCode())
                    .eq(StoreProduct::getUpdateFlag, false)
                    .eq(StoreProduct :: getIsShow, true)
                    .eq(StoreProduct :: getIsDel, false)
                    .set(StoreProduct::getIsShow, false)
                    .set(StoreProduct::getStock, 0)
                    .set(StoreProduct::getLastPushTime, new Date())
                    .set(StoreProduct::getIsTusou, false)
                    );
            // 下架所有sku库存
            storeProductService.downloadSku(ProductTypeEnum.VIETTI.getCode());

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return false;
    }

    /**
     * 商品构建处理
     * @Description:  
     * @author daigb 
     * @param @param products
     * @return void
     * @throws
     */
    private void buildProduct(List<ViettiProduct> products) {
        try {
            for (ViettiProduct product : products) {
                List<ViettiProductSku> skus = viettiProductSkuService.list(Wrappers.<ViettiProductSku>lambdaQuery()
                        .eq(ViettiProductSku :: getProductId, product.getProductId())
                        .isNotNull(ViettiProductSku::getSize)
                        .gt(ViettiProductSku :: getStock, 0)
                        );
                if (CollectionUtils.isEmpty(skus)) {
                    continue;
                }
                // 库存计算
                int stock = 0;
                for (ViettiProductSku sku : skus) {
                    stock += sku.getStock();
                }
                if(CollectionUtils.isEmpty(JSONArray.parseArray(product.getPhotos(),String.class))){
                    log.info("--------------- 该商品: {} 没有图片, 不进行下放 ---------------",product.getProductId());
                    continue;
                }

                // 构建实体
                StoreProductCrmebRequest storeProductCrmebRequest = sourceViettiProductUtil.buildViettiProduct(product, skus);
                // 数据保存
                StoreProduct storeProduct = storeProductService.getByBarCode(storeProductCrmebRequest.getBarCode(), storeProductCrmebRequest.getSuppliersId(), storeProductCrmebRequest.getKeyword());
                boolean crmebUpdate = true;
                if (null != storeProduct && null != storeProduct.getLastPushTime()) {
                    long time = (System.currentTimeMillis() - storeProduct.getLastPushTime().getTime()) / 1000 / 60;
                    if (60 > time) {
                        log.info("--------------- 该商品: {} 上次vietti更新时间: {} 小于一小时, 不进行更新 ---------------", storeProductCrmebRequest.getBarCode(), storeProduct.getLastPushTime());
                        crmebUpdate = false;
                        storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate()
                                .eq(StoreProduct::getId, storeProduct.getId())
                                .set(StoreProduct::getUpdateFlag, true)
                                );
                    }
                }
                if (crmebUpdate) {
                    storeProductService.saveOtProduct(storeProductCrmebRequest, storeProduct, stock);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public void changeProduct() {
        int count = storeProductService.count(Wrappers.<StoreProduct>lambdaQuery()
                .eq(StoreProduct :: getIsEurope, 9)
                );
        int pageSize = 100;
        int maxPage = (count + pageSize - 1) / pageSize;
        for(int i=0; i<=maxPage; i++) {
            PageHelper.startPage(i, pageSize);
            List<StoreProduct> storeProducts = storeProductService.list(Wrappers.<StoreProduct>lambdaQuery()
                .eq(StoreProduct :: getIsEurope, 9)
                );
            PageInfo<StoreProduct> pageInfo = PageInfo.of(storeProducts);
            List<StoreProduct> products = pageInfo.getList();
            for(StoreProduct product : products) {
                String name = product.getStoreName().replace("\"", "");
                String[] infos = StringUtils.isEmpty(product.getStoreInfo()) ? new String[0] : product.getStoreInfo().split("\n");
                
                CategoryMatch nameMatch = categoryMatchService.getOne(Wrappers.<CategoryMatch>lambdaQuery()
                        .eq(CategoryMatch :: getType, 0)
                        .eq(CategoryMatch :: getCategoryName, name)
                        .last("LIMIT 1")
                        );
                String storeName = null == nameMatch ? product.getStoreName() : nameMatch.getOthCategoryName();
                StringBuilder sb = new StringBuilder();
                for(int z=0; z<infos.length; z++) {
                    CategoryMatch infoMatch = categoryMatchService.getOne(Wrappers.<CategoryMatch>lambdaQuery()
                            .eq(CategoryMatch :: getType, 1)
                            .eq(CategoryMatch :: getCategoryName, infos[z])
                            .last("LIMIT 1")
                            );
                    sb.append(null == infoMatch ? infos[z] : infoMatch.getOthCategoryName());
                    if(z+1 < infos.length) {
                        sb.append("\n");
                    }
                }
                
                storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate()
                        .eq(StoreProduct :: getId, product.getId())
                        .set(StoreProduct :: getStoreName, storeName)
                        .set(StoreProduct :: getStoreInfo, sb.toString())
                        );
            }
            
        }
        
        
    }
    
}
